package mysql

import (
	"strconv"
	"time"

	"github.com/convee/goblog/internal/pkg/model"
	"github.com/convee/goblog/pkg/logger"
	"go.uber.org/zap"
)

func UpdateOrAddVisitLogCount(visitlog model.Visitlog) (id int, err error) {
	rs, err := db.Exec("UPDATE visit_log SET click_count=click_count+1 WHERE ip=? AND visit_date=?", visitlog.Ip, visitlog.VisitDate.Local().Format("2006-01-02"))
	if err != nil {
		return
	}
	rows64, err := rs.RowsAffected()
	if rows64 > 0 {
		return int(rows64), err
	}
	rs, err = db.Exec("insert into visit_log (ip, country,province,city,visit_date,click_count) values (?,?, ?,?,?,?)",
		visitlog.Ip, visitlog.Country, visitlog.Province, visitlog.City, visitlog.VisitDate, visitlog.ClickCount)
	if err != nil {
		return
	}
	id64, err := rs.LastInsertId()
	return int(id64), err
}

// 当日点击量
func GetVisitLogClickCount(visitDate time.Time) (clickCount int) {
	row := db.QueryRow("SELECT SUM(click_count) click_count FROM `visit_log` WHERE visit_date=?", visitDate.Local().Format("2006-01-02"))
	row.Scan(clickCount)
	return
}

// 总点击量
func GetAllVisitLogClickCount() (clickCount int) {
	row := db.QueryRow("SELECT SUM(visit_count) visit_count FROM `visit_log`")
	row.Scan(clickCount)
	return clickCount
}

// 当日访问量
func GetVisitLogCount(visitDate time.Time) (int, error) {
	var count *int
	row := db.QueryRow("SELECT COUNT(click_count) click_count FROM `visit_log` WHERE visit_date=?", visitDate.Local().Format("2006-01-02"))
	err := row.Scan(&count)
	if err != nil {
		return 0, err
	}
	return *count, err
}

// 总访问量
func GetAllVisitLogkCount() (int, error) {
	var count *int
	row := db.QueryRow("SELECT COUNT(click_count) visit_count FROM `visit_log`")
	err := row.Scan(&count)
	if err != nil {
		return 0, err
	}
	return *count, err
}
func VisitLogPageList(params PageParams) (pages []model.Visitlog, err error) {
	querySql := "SELECT id,ip, country,province,city,visit_date,click_count FROM `visit_log`"

	querySql += " order by visit_date desc,click_count desc"

	if params.PerPage > 0 && params.Page > 0 {
		offset := (params.Page - 1) * params.PerPage
		querySql += " limit " + strconv.Itoa(offset) + "," + strconv.Itoa(params.PerPage)
	}
	rows, err := db.Query(querySql)
	if err != nil {
		logger.Error("VisitLogPageListError", zap.Error(err))
		return
	}
	if rows.Err() != nil {
		logger.Error("VisitLogPageListError", zap.Error(rows.Err()))
		return
	}
	defer rows.Close()
	for rows.Next() {
		var page model.Visitlog
		_ = rows.Scan(&page.Id, &page.Ip, &page.Country, &page.Province, &page.City, &page.VisitDate, &page.ClickCount)
		pages = append(pages, page)
	}
	return
}
